package com.code.aspect;

import com.code.common.enums.ResultCode;
import com.code.common.exceptions.BusinessException;
import com.code.common.util.StringUtil;
import com.code.common.web.annotations.SuperAdmin;
import com.code.user.model.bo.LoginTokenBO;
import com.code.user.model.po.User;
import com.code.user.token.helper.LoginTokenHelper;
import com.code.user.token.service.LoginTokenService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 超级管理员切面
 *
 * @author tangyifei
 **/
@Aspect
@Configuration
@Slf4j
public class SuperAdminAspect {

    @Resource
    private LoginTokenService loginTokenService;

    @Before("execution(* com.code.web ..*(..) )")
    public void interceptor(JoinPoint joinPoint) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SuperAdmin superAdmin = method.getAnnotation(SuperAdmin.class);
        if (null != superAdmin) {
            // 从请求头中获取tokenId，就是token
            String loginTokenId = LoginTokenHelper.getLoginTokenId();
            User loginUser = null;
            if (StringUtil.isNotEmpty(loginTokenId)) {
                LoginTokenBO loginTokenBO = loginTokenService.getById(loginTokenId);
                if (null != loginTokenBO) {
                    loginUser = loginTokenBO.getLoginUser();
                }
            }

            if (null != loginUser && null != loginUser.getId()) {
                int isAdmin = loginUser.getIsAdmin();
                if (isAdmin == 1) {
                    return;
                }
            }
            throw new BusinessException(ResultCode.SUPER_ADMIN_ERROR);
        }
    }

}
